import { useState, useRef, useEffect } from 'react';
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { LLMChain } from "langchain/chains";
import ReactMarkdownComponent from './components/reactMarkdown';
export default function PromptTemplate() {
  const [messages, setMessages] = useState<Array<{role: string, content: string}>>([]);
  const [industry, setIndustry] = useState("金融科技");
  const [question, setQuestion] = useState("如何降低支付系统的欺诈风险");
  const [specifics, setSpecifics] = useState("实时交易监控");
  const [loading, setLoading] = useState(false);
  const chatContainerRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [messages]);

  const chatModel = new ChatOpenAI({
    modelName: "gpt-3.5-turbo",
    configuration: {
      apiKey: 'xxx',
      baseURL: 'https://xxx'
    },
  });

  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "你是一个专业的{industry}顾问"],
    ["human", "请帮我分析以下问题：{question}"],
    ["ai", "我已经分析了这个问题，我的初步建议是："],
    ["human", "请提供更详细的解决方案关于：{specifics}"],
  ]);

  const chain = new LLMChain({
    llm: chatModel,
    prompt,
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!industry || !question || !specifics) return;

    setLoading(true);
    try {
      // 添加用户消息到聊天记录
      setMessages(prev => [...prev, {
        role: 'user',
        content: `行业: ${industry}\n问题: ${question}\n具体要求: ${specifics}`
      }]);

      // 调用LLM链获取结果
      const response = await chain.call({
        industry, question, specifics
      });

      // 添加AI回复到聊天记录
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: response.text
      }]);

      // 清空输入
      setIndustry("");
      setQuestion("");
      setSpecifics("");
    } catch (error) {
      console.error("调用出错:", error);
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: "抱歉，处理请求时出错，请稍后重试"
      }]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      maxWidth: '800px',
      margin: '0 auto',
      padding: '20px',
      fontFamily: 'Arial, sans-serif'
    }}>
      <h1 style={{ textAlign: 'center', color: '#333' }}>提示模板聊天</h1>

      {/* 聊天消息区域 */}
      <div
        ref={chatContainerRef}
        style={{
          height: '350px',
          border: '1px solid #e0e0e0',
          borderRadius: '8px',
          marginBottom: '20px',
          overflowY: 'auto',
          backgroundColor: '#f9f9f9'
        }}
      >
        {messages.length === 0 ? (
          <div style={{
            textAlign: 'center',
            color: '#666',
            marginTop: '150px'
          }}>
            开始您的第一次咨询吧！
          </div>
        ) : (
          messages.map((msg, index) => (
            <div key={index} style={{
              margin: '10px 0',
              display: 'flex',
              flexDirection: msg.role === 'user' ? 'row-reverse' : 'row'
            }}>
              <div style={{
                maxWidth: '70%',
                padding: '12px 15px',
                borderRadius: '18px',
                backgroundColor: msg.role === 'user' ? '#dcf8c6' : '#ffffff',
                border: '1px solid #e0e0e0',
                boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
              }}>
                <strong style={{ color: msg.role === 'user' ? '#075e54' : '#333' }}>
                  {msg.role === 'user' ? '我' : 'AI'}:
                </strong>
                <div style={{ wordBreak: 'break-word', marginTop: '5px' }}>
                  {/* {msg.content} */}
                  <ReactMarkdownComponent content={msg.content} />
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* 输入表单区域 用户自定义模板中的变量 */}
      <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', color: '#666' }}>行业领域</label>
            <input
              type="text"
              value={industry}
              onChange={(e) => setIndustry(e.target.value)}
              style={{
                width: '100%',
                padding: '10px',
                borderRadius: '4px',
                border: '1px solid #ddd'
              }}
              placeholder="输入行业领域"
            />
          </div>
        </div>

        <div>
          <label style={{ display: 'block', marginBottom: '5px', color: '#666' }}>核心问题</label>
          <input
            type="text"
            value={question}
            onChange={(e) => setQuestion(e.target.value)}
            style={{
              width: '100%',
              padding: '10px',
              borderRadius: '4px',
              border: '1px solid #ddd'
            }}
            placeholder="输入您的核心问题"
            required
          />
        </div>

        <div>
          <label style={{ display: 'block', marginBottom: '5px', color: '#666' }}>具体要求</label>
          <input
            type="text"
            value={specifics}
            onChange={(e) => setSpecifics(e.target.value)}
            style={{
              width: '100%',
              padding: '10px',
              borderRadius: '4px',
              border: '1px solid #ddd'
            }}
            placeholder="输入具体要求"
            required
          />
        </div>

        <button
          type="submit"
          disabled={loading || !question || !specifics}
          style={{
            padding: '12px 20px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '16px',
            cursor: 'pointer',
            transition: 'backgroundColor 0.3s',
            disabled: {
              backgroundColor: '#cccccc',
              cursor: 'not-allowed'
            }
          }}
        >
          {loading ? '处理中...' : '生成回复'}
        </button>
      </form>
    </div>
  );
}
;
